const express = require("express");
const router = express.Router();
const path = require("path");
const multer = require("multer");
const fs = require("fs");
const md5 = require('md5');

let storage = multer.diskStorage({
 destination: function (req, file, cb) {
   cb(null, path.join(__dirname, '..', 'public', 'tmp'))
 },
 filename: function (req, file, cb) {
   let fileFormat =(file.originalname).split(".");
   cb(null, file.fieldname + '-' + md5(file) + "." + fileFormat[fileFormat.length - 1]);
 }
})

//中间件
const upload = multer({
  storage: storage
});

const single = upload.single("myfile");
// const fields = upload.fields([
//   {name: "myfile", maxCount: 1},
//   {name: "album", maxCount: 3}
// ]);

//上传图像
router.post('/upload', single, function(req, res){
  if (req.file) {
       //res.send('文件上传成功')
       // console.log(req.file);
       //console.log(req.body.album);
       let file = req.file
       let album = req.body.album;
       let sourceFile = path.join(__dirname, '..', 'public', 'tmp', file.filename)
       let destPath = path.join(__dirname, '..', 'public', 'images', album, file.filename)

       fs.rename(sourceFile, destPath, function (err) {
         if (err) throw err;
         fs.stat(destPath, function (err, stats) {
           if (err) throw err;
           //console.log('stats: ' + JSON.stringify(stats));
         });
       });
   }
})

router.get("/read/:album/:imgname", function(req, res){
  // console.log('------------------------------------------------')
  // console.log("public/images/" + req.params.album + '/' + req.params.imgname);
  //创建一个读取流
  const rs = fs.createReadStream("public/images/" + req.params.album + '/' + req.params.imgname);
  req.params.imgname
  rs.pipe(res);
})

router.post("/list", function(req, res){
  let name = req.body.name;
  let namePath = path.join(__dirname, '..', 'public', 'images', name);
  if(name !== '全部') {
    readAlbum(namePath).then(images => {
      console.log(images);
      res.send({status: 0, list: images})
    })
    .catch(e => {
      res.send({status: -1})
    })
  }
})


//删除图像
router.post('/delete', function(req, res){
  let album = req.body.album;
  let name = req.body.name;
  console.log(name);
  let namePath = path.join('./public/images', album, name);
  fs.access(namePath, function(err){
    if(err){
      res.send({
        status: -2,
        message: '图片不存在'
      });
    }
    fs.unlink(namePath, function(err){
      if(err){
        res.send({status: -1});
      }
      res.send({status: 0});
    })
  })
})


function readAlbum(path){
  return new Promise(function(resolve, reject){
    fs.readdir(path, function(err, files){
      if(err){
        reject(err);
      }
      resolve(files);
    })
  })
}

module.exports = router;
